package com.joymart.common.data.jdbc;

import org.json.JSONTokener;
import org.postgresql.util.PGobject;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.lang.Nullable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

public class EnhancedColumnMapRowMapper extends ColumnMapRowMapper {
    @Override
    @Nullable
    protected Object getColumnValue(ResultSet rs, int index) throws SQLException {

        Object object = rs.getObject(index);
        if(object instanceof PGobject && Arrays.asList("json", "jsonb").contains(((PGobject) object).getType())){
            if(((PGobject) object).isNull()) {
                return null;
            }
            String jsonString = rs.getString(index);
            return new JSONTokener(jsonString).nextValue();
        }else{
            return JdbcUtils.getResultSetValue(rs, index);
        }

    }
}
